package com.ossean;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import com.ossean.dao.TransferPrjDao;

@Component
public class TransferManageProcess {
	
	@Resource
	private TransferPrjDao transferPrjDao;
	private String sourceTableName = TableName.eddRelationTableName;
	private static Logger logger = Logger.getLogger(TransferManageProcess.class);
	public static Map<String,Boolean> gatherState = new HashMap<String,Boolean>(); //
	private ExecutorService pool = Executors.newFixedThreadPool(20);
    int batchSize = 500000;
	public void start(){
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/applicationContext*.xml");
		long startTime = System.currentTimeMillis();
		int maxId = transferPrjDao.selectMaxRelationId(sourceTableName);
		int loop;
		if (maxId % batchSize == 0)
			loop = maxId/batchSize;
		else
			loop = maxId/batchSize+1;
		//每个线程处理150000个项目
		for(int i = 0;i < loop;i++){
			Boolean state = gatherState.get("PrjThread"+(i+1));
			if(state == null || state == false){
				gatherState.put("PrjThread"+(i+1), true);
			}
			else if(state == true){
				continue;
			}
			MultiThreadTransferProjects thread = (MultiThreadTransferProjects)applicationContext.getBean("multiThreadTransferProjects");
			
			if(i==(loop-1))
				thread.setParameters(i*batchSize,maxId,"PrjThread"+(i+1));
			else
				thread.setParameters(i*batchSize,(i+1)*batchSize,"PrjThread"+(i+1));
			pool.execute(thread);
		}
		logger.info("current env thread nums: "+((ThreadPoolExecutor)pool).getActiveCount());
		System.out.println("已经开启所有的子线程");  
        pool.shutdown();  
        System.out.println("shutdown()：启动一次顺序关闭，执行以前提交的任务，但不接受新任务。");  
        while(true){  
            if(pool.isTerminated()){  
                System.out.println("所有的子线程都结束了！");
                System.out.println("cost time: "+(System.currentTimeMillis()-startTime)/1000+"seconds");
                break;  
            }
            try {
            	logger.info(".......sleeping......");
				Thread.sleep(1*60*1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
				logger.error(e);
			}    
        }  
		System.gc();  //手动垃圾回收
		
	}
	
	public static void main(String[] args) throws InterruptedException {
		
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/applicationContext*.xml");
		TransferManageProcess main = applicationContext.getBean(TransferManageProcess.class);
		main.start();
	}

}
